import Pagination from "@/components/Pagination";
import { mapGetters } from 'vuex';
import { alertWithCallback, alertMessage, isValidateNull } from '../../../utils/utils';
import { validPhone } from "@/utils/validate";
import { getIncomeType, saveSaleData, getDataList, deleteSelectedData } from "@/views/data-manage/data.service";

export default {
  name: 'data-list',
  components: { Pagination },
  directives: {},
  data() {
    return {
      totalNum: 0, // 数据总数
      pageNum: 1, // 页数
      recordNum: 100, // 分页组件默认的页数, 分页里的select默认10, 20, 50
      queryString: "", // 搜索字段
      searchCriteria: {}, // 搜索对象
      data: [], // 列表数据
      loading: true, // table loading
      detailDialogVisible: false, // 数据详情模态窗
      editDialogVisible: false, // 编辑详情模态窗
      selectedDataDetail: {}, // 选中数据详情
      editForm: {}, // 编辑表单
      editRules: {
        trueName: [{ required: true, trigger: "change", validator: isValidateNull }],
        mobileNumber: [
          { required: true, trigger: "change", validator: isValidateNull },
          { trigger: "change", validator: validPhone, message: '联系方式格式有误' }
        ],
        enumSex: [{ required: true, trigger: "change", validator: isValidateNull }],
        age: [{ required: true, trigger: "change", validator: isValidateNull }],
        birthday: [{ required: true, trigger: "change", validator: isValidateNull }],
        income: [{ required: true, trigger: "change", validator: isValidateNull }],
        family: [{ required: true, trigger: "change", validator: isValidateNull }],
        positionName: [{ required: true, trigger: "change", validator: isValidateNull }],
        liveAddress: [{ required: true, trigger: "change", validator: isValidateNull }],
        lifeAddress: [{ required: true, trigger: "change", validator: isValidateNull }],
        nowHouse: [{ required: true, trigger: "change", validator: isValidateNull }],
        visitProject: [{ required: true, trigger: "change", validator: isValidateNull }],
        visitDate: [{ required: true, trigger: "change", validator: isValidateNull }],
        recordDate: [{ required: true, trigger: "change", validator: isValidateNull }],
        counselor: [{ required: true, trigger: "change", validator: isValidateNull }]
      }, // 编辑表单验证规则
      dialogTitle: '', // 编辑弹窗标题
      incomeTypes: [], // 收入评估
      filename: '销售数据导出',
      autoWidth: true,
      bookType: 'xlsx',
      file_url: process.env.VUE_APP_BASE_API, // 头像url
      checkedRows: [] // table checkbox选中数据
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getDataList();
    this.getIncomeTypes();
  },
  methods: {
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['序号', '姓名', '联系方式', '性别', '年龄', '生日', '收入评估', '职业工作', '到访项目', '到访日期', '录入日期', '置业顾问', '家庭状况', '居住区域', '生活区域', '现住小区', '成交项目', '成交房号', '成交面积', '成交日期', '备注']
        const filterVal = ['index', 'trueName', 'mobileNumber', 'enumSex', 'age', 'birthday', 'income', 'positionName', 'visitProject', 'visitDate', 'recordDate', 'counselor', 'family', 'liveAddress', 'lifeAddress', 'nowHouse', 'dealProject', 'dealRoom', 'dealArea', 'dealDate', 'remark']
        const list = this.data
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename + "_" + new Date().valueOf(),
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v, index) => filterVal.map(j => {
        if (j === 'index') {
          return index + 1
        } else if (j === 'income') {
          return this.formatIncome({ income: v[j] })
        } else {
          return v[j]
        }
      }))
    },
    // 自定义排序column参数为一个对象包含需要排序的属性和排序方法
    sortColumn(column) {
      if (column.order == "ascending") {
        this.searchCriteria.sortType = "asc"
      } else if (column.order == "descending") {
        this.searchCriteria.sortType = "desc"
      } else {
        return;
      }
      let field = column.prop;
      if (field == "trueName") {
        field = "true_name";
      } else {
        field = "mobile_number";
      }
      this.searchCriteria.sortField = field;
      this.search();
    },

    // 格式化日期收入
    formatIncome(row, column) {
      let result = row.income;
      this.incomeTypes.forEach(item => {
        if (item.itemValue == row.income) {
          result = item.itemName;
        }
      });
      return result;
    },

    // 获取列表
    getDataList() {
      this.loading = true;
      this.searchCriteria.pageNum = this.pageNum;
      this.searchCriteria.recordNum = this.recordNum;
      getDataList(this.searchCriteria).then(res => {
        this.totalNum = res.dataCount;
        this.data = res.data;
        this.loading = false;
      });
    },

    // 根据关键字进行搜索
    search() {
      this.pageNum = 1;
      this.getDataList();
    },

    // 重置搜索
    reset() {
      this.pageNum = 1;
      this.searchCriteria = {};
      this.getDataList();
    },

    // 打开新建、编辑窗体
    openEditDialog(type, selectedData) {
      this.getIncomeTypes();
      if (type === 'create') {
        this.dialogTitle = '新建';
        this.$nextTick(() => {
          // 重置必填项
          this.editForm = {
            enumSex: '0'
          };
          this.$refs.dataForm.resetFields();
        });
      } else {
        this.dialogTitle = '编辑';
        this.$nextTick(() => {
          selectedData.income = "" + selectedData.income;
          this.editForm = Object.assign({}, selectedData);
          this.$refs.dataForm.resetFields();
        });
      }
      this.editDialogVisible = true;
    },

    // 创建或者编辑信息
    save() {
      // 表单验证
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          saveSaleData(this.editForm).then((res) => {
            this.editDialogVisible = false;
            alertMessage(res.message);
            this.reset();
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      });
    },

    // 删除选中数据
    deleteSelectedData(id) {
      if (id) {
        alertWithCallback('此操作将永久删除该数据, 是否继续?', '提示').then(() => {
          deleteSelectedData([id]).then((res) => {
            alertMessage(res.message);
            this.reset();
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
      } else {
        if (this.checkedRows.length == 0) {
          alertMessage('请选择记录', 'warning');
        } else {
          alertWithCallback('此操作将永久删除该数据, 是否继续?', '提示').then(() => {
            const ids = [];
            this.checkedRows.forEach(item => {
              ids.push(item.objectId)
            });
            deleteSelectedData(ids).then((res) => {
              alertMessage(res.message);
              this.reset();
            }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
          }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      }
    },

    // 处理checkbox选中行数据
    handleSelectionChange(val) {
      this.checkedRows = val;
    },

    // 获取收入评估类型
    getIncomeTypes() {
      getIncomeType().then(res => {
        this.incomeTypes = res.data;
      });
    },

    // 重置密码
    resetPwd() {
      this.editForm.password = '123456';
      alertMessage('重置密码成功, 请提交修改信息');
    },

    handleImportSuccess(res, file) {
      alertMessage('导入成功');
      this.reset();
    }
  }
}
